#include "ProtocolAdapters.h"
#include <QDebug>
#include <QDateTime>
#include <algorithm>
#include <cstring>

namespace ProtocolAdapters 
{
    // ========== QtNativeAdapter 实现 ==========
    
    std::vector<uint8_t> QtNativeAdapter::serializeMessage(const UniversalProtocol::UniversalMessage& message) 
    {
        // 根据消息类型创建对应的Qt数据包
        std::shared_ptr<GamePacket> qtPacket;
        
        switch (message.type) 
        {
            case UniversalProtocol::MessageType::PLAYER_JOIN:
            {
                qtPacket = std::make_shared<GamePacket>(PacketType::PLAYER_JOIN, message.playerId);
                break;
            }
            case UniversalProtocol::MessageType::PLAYER_LEAVE:
            {
                qtPacket = std::make_shared<GamePacket>(PacketType::PLAYER_LEAVE, message.playerId);
                break;
            }
            case UniversalProtocol::MessageType::GAME_START:
            {
                qtPacket = std::make_shared<GamePacket>(PacketType::GAME_START, message.playerId);
                break;
            }
            case UniversalProtocol::MessageType::GAME_STATUS:
            {
                auto statusMsg = static_cast<const UniversalProtocol::GameStatusMessage&>(message);
                PlayerGameData qtPlayerData = convertToPlayerGameData(statusMsg.playerData);
                MonsterData qtMonsterData = convertToMonsterData(statusMsg.monsterData);
                
                auto statusPacket = std::make_shared<GameStatusPacket>(message.playerId, qtPlayerData, qtMonsterData, 
                                                                      QString::fromStdString(statusMsg.message));
                qtPacket = statusPacket;
                break;
            }
            case UniversalProtocol::MessageType::ATTACK:
            {
                auto attackMsg = static_cast<const UniversalProtocol::AttackMessage&>(message);
                auto attackPacket = std::make_shared<AttackPacket>(PacketType::ATTACK, message.playerId, 
                                                                   attackMsg.damage, attackMsg.targetHealth, 
                                                                   QString::fromStdString(attackMsg.message));
                qtPacket = attackPacket;
                break;
            }
            case UniversalProtocol::MessageType::LEVEL_UP:
            {
                auto levelUpMsg = static_cast<const UniversalProtocol::LevelUpMessage&>(message);
                PlayerGameData qtPlayerData = convertToPlayerGameData(levelUpMsg.newPlayerData);
                
                auto levelUpPacket = std::make_shared<LevelUpPacket>(message.playerId, qtPlayerData, 
                                                                     QString::fromStdString(levelUpMsg.message));
                qtPacket = levelUpPacket;
                break;
            }
            case UniversalProtocol::MessageType::COMBAT_MESSAGE:
            {
                auto combatMsg = static_cast<const UniversalProtocol::CombatMessage&>(message);
                auto combatPacket = std::make_shared<CombatMessagePacket>(message.playerId, 
                                                                          QString::fromStdString(combatMsg.message));
                qtPacket = combatPacket;
                break;
            }
            default:
                // 不支持的消息类型，创建基础包
                qtPacket = std::make_shared<GamePacket>(convertToPacketType(message.type), message.playerId);
                break;
        }
        
        // 设置时间戳
        qtPacket->timestamp = message.timestamp > 0 ? message.timestamp : QDateTime::currentMSecsSinceEpoch();
        
        // 序列化为Qt二进制格式
        QByteArray qtData = qtPacket->serialize();
        
        // 转换为std::vector<uint8_t>
        std::vector<uint8_t> result(qtData.size());
        std::memcpy(result.data(), qtData.constData(), qtData.size());
        
        return result;
    }
    
    std::unique_ptr<UniversalProtocol::UniversalMessage> QtNativeAdapter::deserializeMessage(const std::vector<uint8_t>& data) 
    {
        // 转换为QByteArray
        QByteArray qtData(reinterpret_cast<const char*>(data.data()), static_cast<int>(data.size()));
        
        // 使用Qt的反序列化
        auto qtPacket = GamePacket::deserialize(qtData);
        if (!qtPacket) 
        {
            return nullptr;
        }
        
        // 先保存基本信息，避免在move后访问
        PacketType packetType = qtPacket->type;
        quint32 playerId = qtPacket->playerId;
        quint32 timestamp = qtPacket->timestamp;
        
        // 转换为通用消息格式
        std::unique_ptr<UniversalProtocol::UniversalMessage> universalMsg;
        
        switch (packetType) 
        {
            case PacketType::PLAYER_JOIN:
            {
                auto joinMsg = std::make_unique<UniversalProtocol::PlayerJoinMessage>();
                joinMsg->playerId = playerId;
                joinMsg->timestamp = timestamp;
                universalMsg = std::move(joinMsg);
                break;
            }
            case PacketType::PLAYER_LEAVE:
            {
                auto leaveMsg = std::make_unique<UniversalProtocol::PlayerJoinMessage>();
                leaveMsg->type = UniversalProtocol::MessageType::PLAYER_LEAVE;
                leaveMsg->playerId = playerId;
                leaveMsg->timestamp = timestamp;
                universalMsg = std::move(leaveMsg);
                break;
            }
            case PacketType::GAME_START:
            {
                auto startMsg = std::make_unique<UniversalProtocol::PlayerJoinMessage>();
                startMsg->type = UniversalProtocol::MessageType::GAME_START;
                startMsg->playerId = playerId;
                startMsg->timestamp = timestamp;
                universalMsg = std::move(startMsg);
                break;
            }
            case PacketType::GAME_STATUS:
            {
                // 转换为shared_ptr，然后进行dynamic_pointer_cast
                std::shared_ptr<GamePacket> sharedPacket = std::move(qtPacket);
                auto qtStatusPacket = std::dynamic_pointer_cast<GameStatusPacket>(sharedPacket);
                if (qtStatusPacket) 
                {
                    auto statusMsg = std::make_unique<UniversalProtocol::GameStatusMessage>();
                    statusMsg->playerId = playerId;
                    statusMsg->timestamp = timestamp;
                    statusMsg->playerData = convertPlayerGameData(qtStatusPacket->playerData);
                    statusMsg->monsterData = convertMonsterData(qtStatusPacket->monsterData);
                    statusMsg->message = qtStatusPacket->message.toStdString();
                    universalMsg = std::move(statusMsg);
                }
                break;
            }
            case PacketType::ATTACK:
            {
                // 转换为shared_ptr，然后进行dynamic_pointer_cast
                std::shared_ptr<GamePacket> sharedPacket = std::move(qtPacket);
                auto qtAttackPacket = std::dynamic_pointer_cast<AttackPacket>(sharedPacket);
                if (qtAttackPacket) 
                {
                    auto attackMsg = std::make_unique<UniversalProtocol::AttackMessage>();
                    attackMsg->playerId = playerId;
                    attackMsg->timestamp = timestamp;
                    attackMsg->damage = qtAttackPacket->damage;
                    attackMsg->targetHealth = qtAttackPacket->targetHealth;
                    attackMsg->message = qtAttackPacket->message.toStdString();
                    universalMsg = std::move(attackMsg);
                }
                break;
            }
            case PacketType::LEVEL_UP:
            {
                // 转换为shared_ptr，然后进行dynamic_pointer_cast
                std::shared_ptr<GamePacket> sharedPacket = std::move(qtPacket);
                auto qtLevelUpPacket = std::dynamic_pointer_cast<LevelUpPacket>(sharedPacket);
                if (qtLevelUpPacket) 
                {
                    auto levelUpMsg = std::make_unique<UniversalProtocol::LevelUpMessage>();
                    levelUpMsg->playerId = playerId;
                    levelUpMsg->timestamp = timestamp;
                    levelUpMsg->newPlayerData = convertPlayerGameData(qtLevelUpPacket->newPlayerData);
                    levelUpMsg->message = qtLevelUpPacket->message.toStdString();
                    universalMsg = std::move(levelUpMsg);
                }
                break;
            }
            case PacketType::COMBAT_MESSAGE:
            {
                // 转换为shared_ptr，然后进行dynamic_pointer_cast
                std::shared_ptr<GamePacket> sharedPacket = std::move(qtPacket);
                auto qtCombatPacket = std::dynamic_pointer_cast<CombatMessagePacket>(sharedPacket);
                if (qtCombatPacket) 
                {
                    auto combatMsg = std::make_unique<UniversalProtocol::CombatMessage>();
                    combatMsg->playerId = playerId;
                    combatMsg->timestamp = timestamp;
                    combatMsg->message = qtCombatPacket->message.toStdString();
                    universalMsg = std::move(combatMsg);
                }
                break;
            }
            default:
                return nullptr;
        }
        
        return universalMsg;
    }
    
    bool QtNativeAdapter::canHandle(const std::vector<uint8_t>& data) const 
    {
        // 尝试用Qt的反序列化来检测是否为Qt格式
        QByteArray qtData(reinterpret_cast<const char*>(data.data()), static_cast<int>(data.size()));
        auto qtPacket = GamePacket::deserialize(qtData);
        return qtPacket != nullptr;
    }
    
    // Qt数据类型转换辅助函数
    UniversalProtocol::PlayerAttributes QtNativeAdapter::convertPlayerGameData(const PlayerGameData& qtData) const 
    {
        UniversalProtocol::PlayerAttributes attr;
        attr.level = qtData.level;
        attr.health = qtData.health;
        attr.maxHealth = qtData.maxHealth;
        attr.attackPower = qtData.attackPower;
        attr.defense = qtData.defense;
        attr.critChance = qtData.critChance;
        attr.critMultiplier = qtData.critMultiplier;
        attr.hitChance = qtData.hitChance;
        attr.dodgeChance = qtData.dodgeChance;
        attr.totalKills = qtData.totalKills;
        attr.gameState = static_cast<UniversalProtocol::GameState>(qtData.gameState);
        attr.isInAutoCombat = qtData.isInAutoCombat;
        return attr;
    }
    
    UniversalProtocol::MonsterAttributes QtNativeAdapter::convertMonsterData(const MonsterData& qtData) const 
    {
        UniversalProtocol::MonsterAttributes attr;
        attr.level = qtData.level;
        attr.health = qtData.health;
        attr.maxHealth = qtData.maxHealth;
        attr.attackPower = qtData.attackPower;
        attr.defense = qtData.defense;
        attr.critChance = qtData.critChance;
        attr.critMultiplier = qtData.critMultiplier;
        attr.hitChance = qtData.hitChance;
        attr.dodgeChance = qtData.dodgeChance;
        attr.name = qtData.name.toStdString();
        return attr;
    }
    
    PlayerGameData QtNativeAdapter::convertToPlayerGameData(const UniversalProtocol::PlayerAttributes& universalData) const 
    {
        PlayerGameData qtData;
        qtData.level = universalData.level;
        qtData.health = universalData.health;
        qtData.maxHealth = universalData.maxHealth;
        qtData.attackPower = universalData.attackPower;
        qtData.defense = universalData.defense;
        qtData.critChance = universalData.critChance;
        qtData.critMultiplier = universalData.critMultiplier;
        qtData.hitChance = universalData.hitChance;
        qtData.dodgeChance = universalData.dodgeChance;
        qtData.totalKills = universalData.totalKills;
        qtData.gameState = static_cast<GameState>(universalData.gameState);
        qtData.isInAutoCombat = universalData.isInAutoCombat;
        return qtData;
    }
    
    MonsterData QtNativeAdapter::convertToMonsterData(const UniversalProtocol::MonsterAttributes& universalData) const 
    {
        MonsterData qtData;
        qtData.level = universalData.level;
        qtData.health = universalData.health;
        qtData.maxHealth = universalData.maxHealth;
        qtData.attackPower = universalData.attackPower;
        qtData.defense = universalData.defense;
        qtData.critChance = universalData.critChance;
        qtData.critMultiplier = universalData.critMultiplier;
        qtData.hitChance = universalData.hitChance;
        qtData.dodgeChance = universalData.dodgeChance;
        qtData.name = QString::fromStdString(universalData.name);
        return qtData;
    }
    
    UniversalProtocol::MessageType QtNativeAdapter::convertPacketType(PacketType qtType) const 
    {
        switch (qtType) 
        {
            case PacketType::PLAYER_JOIN: return UniversalProtocol::MessageType::PLAYER_JOIN;
            case PacketType::PLAYER_LEAVE: return UniversalProtocol::MessageType::PLAYER_LEAVE;
            case PacketType::GAME_START: return UniversalProtocol::MessageType::GAME_START;
            case PacketType::GAME_STATUS: return UniversalProtocol::MessageType::GAME_STATUS;
            case PacketType::ATTACK: return UniversalProtocol::MessageType::ATTACK;
            case PacketType::LEVEL_UP: return UniversalProtocol::MessageType::LEVEL_UP;
            case PacketType::COMBAT_MESSAGE: return UniversalProtocol::MessageType::COMBAT_MESSAGE;
            default: return UniversalProtocol::MessageType::PLAYER_JOIN; // 默认值
        }
    }
    
    PacketType QtNativeAdapter::convertToPacketType(UniversalProtocol::MessageType universalType) const 
    {
        switch (universalType) 
        {
            case UniversalProtocol::MessageType::PLAYER_JOIN: return PacketType::PLAYER_JOIN;
            case UniversalProtocol::MessageType::PLAYER_LEAVE: return PacketType::PLAYER_LEAVE;
            case UniversalProtocol::MessageType::GAME_START: return PacketType::GAME_START;
            case UniversalProtocol::MessageType::GAME_STATUS: return PacketType::GAME_STATUS;
            case UniversalProtocol::MessageType::ATTACK: return PacketType::ATTACK;
            case UniversalProtocol::MessageType::LEVEL_UP: return PacketType::LEVEL_UP;
            case UniversalProtocol::MessageType::COMBAT_MESSAGE: return PacketType::COMBAT_MESSAGE;
            default: return PacketType::PLAYER_JOIN; // 默认值
        }
    }
    
    // ========== JsonUniversalAdapter 实现 ==========
    
    std::vector<uint8_t> JsonUniversalAdapter::serializeMessage(const UniversalProtocol::UniversalMessage& message) 
    {
        std::string jsonStr = message.toJson();
        std::vector<uint8_t> result(jsonStr.begin(), jsonStr.end());
        return result;
    }
    
    std::unique_ptr<UniversalProtocol::UniversalMessage> JsonUniversalAdapter::deserializeMessage(const std::vector<uint8_t>& data) 
    {
        std::string jsonStr(data.begin(), data.end());
        
        if (!isValidJsonFormat(jsonStr)) 
        {
            return nullptr;
        }
        
        auto message = UniversalProtocol::MessageFactory::createFromJson(jsonStr);
        if (message) 
        {
            message->fromJson(jsonStr);
        }
        
        return message;
    }
    
    bool JsonUniversalAdapter::canHandle(const std::vector<uint8_t>& data) const 
    {
        std::string jsonStr(data.begin(), data.end());
        return isValidJsonFormat(jsonStr);
    }
    
    bool JsonUniversalAdapter::isValidJsonFormat(const std::string& jsonStr) const 
    {
        // 简单的JSON格式检测
        if (jsonStr.empty()) return false;
        
        // 去除前后空白字符
        size_t start = 0, end = jsonStr.length() - 1;
        while (start < jsonStr.length() && std::isspace(jsonStr[start])) start++;
        while (end > start && std::isspace(jsonStr[end])) end--;
        
        if (start >= jsonStr.length()) return false;
        
        // JSON对象必须以{开始，}结束
        return jsonStr[start] == '{' && jsonStr[end] == '}' && jsonStr.find("\"type\"") != std::string::npos;
    }
    
    // ========== WebSocketAdapter 实现 ==========
    
    std::vector<uint8_t> WebSocketAdapter::serializeMessage(const UniversalProtocol::UniversalMessage& message) 
    {
        // 先用父类方法获取JSON数据
        auto jsonData = JsonUniversalAdapter::serializeMessage(message);
        
        // 包装为WebSocket帧
        return wrapInWebSocketFrame(jsonData);
    }
    
    std::unique_ptr<UniversalProtocol::UniversalMessage> WebSocketAdapter::deserializeMessage(const std::vector<uint8_t>& data) 
    {
        if (!isWebSocketFrame(data)) 
        {
            return nullptr;
        }
        
        // 从WebSocket帧中提取payload
        auto payload = extractFromWebSocketFrame(data);
        
        // 用父类方法解析JSON
        return JsonUniversalAdapter::deserializeMessage(payload);
    }
    
    bool WebSocketAdapter::canHandle(const std::vector<uint8_t>& data) const 
    {
        return isWebSocketFrame(data);
    }
    
    std::vector<uint8_t> WebSocketAdapter::wrapInWebSocketFrame(const std::vector<uint8_t>& payload) const 
    {
        // 简化的WebSocket帧格式实现
        std::vector<uint8_t> frame;
        
        // WebSocket帧头：FIN=1, RSV=000, Opcode=0001(文本帧)
        frame.push_back(0x81);
        
        // Payload长度
        if (payload.size() < 126) 
        {
            frame.push_back(static_cast<uint8_t>(payload.size()));
        } 
        else if (payload.size() < 65536) 
        {
            frame.push_back(126);
            frame.push_back(static_cast<uint8_t>(payload.size() >> 8));
            frame.push_back(static_cast<uint8_t>(payload.size() & 0xFF));
        } 
        else 
        {
            // 简化实现，不支持超大帧
            frame.push_back(127);
            for (int i = 7; i >= 0; --i) 
            {
                frame.push_back(static_cast<uint8_t>((payload.size() >> (i * 8)) & 0xFF));
            }
        }
        
        // 添加payload
        frame.insert(frame.end(), payload.begin(), payload.end());
        
        return frame;
    }
    
    std::vector<uint8_t> WebSocketAdapter::extractFromWebSocketFrame(const std::vector<uint8_t>& frame) const 
    {
        if (frame.size() < 2) return {};
        
        size_t offset = 2; // 跳过基本头部
        size_t payloadLength = frame[1] & 0x7F;
        
        // 处理扩展长度
        if (payloadLength == 126) 
        {
            if (frame.size() < 4) return {};
            payloadLength = (frame[2] << 8) | frame[3];
            offset = 4;
        } 
        else if (payloadLength == 127) 
        {
            if (frame.size() < 10) return {};
            payloadLength = 0;
            for (int i = 2; i < 10; ++i) 
            {
                payloadLength = (payloadLength << 8) | frame[i];
            }
            offset = 10;
        }
        
        // 检查掩码位（客户端到服务器的消息应该有掩码）
        bool masked = (frame[1] & 0x80) != 0;
        if (masked) 
        {
            offset += 4; // 跳过掩码键
        }
        
        if (frame.size() < offset + payloadLength) return {};
        
        // 提取payload（简化实现，忽略掩码处理）
        return std::vector<uint8_t>(frame.begin() + offset, frame.begin() + offset + payloadLength);
    }
    
    bool WebSocketAdapter::isWebSocketFrame(const std::vector<uint8_t>& data) const 
    {
        if (data.size() < 2) return false;
        
        // 检查WebSocket帧的基本格式
        uint8_t firstByte = data[0];
        uint8_t secondByte = data[1];
        
        // 检查FIN位和Opcode
        bool fin = (firstByte & 0x80) != 0;
        uint8_t opcode = firstByte & 0x0F;
        
        // 文本帧(1)或二进制帧(2)
        return fin && (opcode == 1 || opcode == 2);
    }
    
    // ========== BinaryAdapter 实现 ==========
    
    std::vector<uint8_t> BinaryAdapter::serializeMessage(const UniversalProtocol::UniversalMessage& message) 
    {
        std::vector<uint8_t> buffer;
        
        // 写入魔数和版本
        writeBinaryData(buffer, &BINARY_MAGIC, sizeof(BINARY_MAGIC));
        writeBinaryData(buffer, &BINARY_VERSION, sizeof(BINARY_VERSION));
        
        // 写入消息头
        uint16_t msgType = static_cast<uint16_t>(message.type);
        writeBinaryData(buffer, &msgType, sizeof(msgType));
        writeBinaryData(buffer, &message.playerId, sizeof(message.playerId));
        writeBinaryData(buffer, &message.timestamp, sizeof(message.timestamp));
        writeBinaryData(buffer, &message.messageId, sizeof(message.messageId));
        
        // 根据消息类型写入特定数据（简化实现）
        switch (message.type) 
        {
            case UniversalProtocol::MessageType::COMBAT_MESSAGE:
            {
                auto combatMsg = static_cast<const UniversalProtocol::CombatMessage&>(message);
                writeString(buffer, combatMsg.message);
                break;
            }
            // 其他消息类型的序列化...
            default:
                break;
        }
        
        return buffer;
    }
    
    std::unique_ptr<UniversalProtocol::UniversalMessage> BinaryAdapter::deserializeMessage(const std::vector<uint8_t>& data) 
    {
        if (data.size() < sizeof(BINARY_MAGIC) + sizeof(BINARY_VERSION) + 12) 
        {
            return nullptr;
        }
        
        size_t offset = 0;
        
        // 检查魔数
        uint32_t magic;
        readBinaryData(data, offset, &magic, sizeof(magic));
        if (magic != BINARY_MAGIC) return nullptr;
        
        // 检查版本
        uint16_t version;
        readBinaryData(data, offset, &version, sizeof(version));
        if (version != BINARY_VERSION) return nullptr;
        
        // 读取消息头
        uint16_t msgType;
        UniversalProtocol::PlayerId playerId;
        UniversalProtocol::Timestamp timestamp;
        UniversalProtocol::MessageId messageId;
        
        readBinaryData(data, offset, &msgType, sizeof(msgType));
        readBinaryData(data, offset, &playerId, sizeof(playerId));
        readBinaryData(data, offset, &timestamp, sizeof(timestamp));
        readBinaryData(data, offset, &messageId, sizeof(messageId));
        
        // 根据消息类型创建消息对象（简化实现）
        auto message = UniversalProtocol::MessageFactory::createFromType(static_cast<UniversalProtocol::MessageType>(msgType));
        if (message) 
        {
            message->playerId = playerId;
            message->timestamp = timestamp;
            message->messageId = messageId;
        }
        
        return message;
    }
    
    bool BinaryAdapter::canHandle(const std::vector<uint8_t>& data) const 
    {
        if (data.size() < sizeof(BINARY_MAGIC)) return false;
        
        uint32_t magic;
        std::memcpy(&magic, data.data(), sizeof(magic));
        return magic == BINARY_MAGIC;
    }
    
    void BinaryAdapter::writeBinaryData(std::vector<uint8_t>& buffer, const void* data, size_t size) const 
    {
        const uint8_t* bytes = static_cast<const uint8_t*>(data);
        buffer.insert(buffer.end(), bytes, bytes + size);
    }
    
    void BinaryAdapter::readBinaryData(const std::vector<uint8_t>& buffer, size_t& offset, void* data, size_t size) const 
    {
        if (offset + size <= buffer.size()) 
        {
            std::memcpy(data, buffer.data() + offset, size);
            offset += size;
        }
    }
    
    void BinaryAdapter::writeString(std::vector<uint8_t>& buffer, const std::string& str) const 
    {
        uint32_t length = static_cast<uint32_t>(str.length());
        writeBinaryData(buffer, &length, sizeof(length));
        writeBinaryData(buffer, str.data(), str.length());
    }
    
    std::string BinaryAdapter::readString(const std::vector<uint8_t>& buffer, size_t& offset) const 
    {
        uint32_t length;
        readBinaryData(buffer, offset, &length, sizeof(length));
        
        if (offset + length <= buffer.size()) 
        {
            std::string result(reinterpret_cast<const char*>(buffer.data() + offset), length);
            offset += length;
            return result;
        }
        
        return "";
    }
    
    // ========== AdapterManager 实现 ==========
    
    AdapterManager::AdapterManager() 
    {
        // 注册默认适配器
        registerAdapter(std::make_unique<QtNativeAdapter>());
        registerAdapter(std::make_unique<JsonUniversalAdapter>());
        registerAdapter(std::make_unique<WebSocketAdapter>());
        registerAdapter(std::make_unique<BinaryAdapter>());
        
        buildAdapterMap();
    }
    
    void AdapterManager::registerAdapter(std::unique_ptr<UniversalProtocol::IProtocolAdapter> adapter) 
    {
        if (adapter) 
        {
            m_adapters.push_back(std::move(adapter));
            buildAdapterMap();
        }
    }
    
    UniversalProtocol::IProtocolAdapter* AdapterManager::selectAdapter(const std::vector<uint8_t>& data) const 
    {
        for (const auto& adapter : m_adapters) 
        {
            if (adapter->canHandle(data)) 
            {
                return adapter.get();
            }
        }
        return nullptr;
    }
    
    UniversalProtocol::IProtocolAdapter* AdapterManager::getAdapter(UniversalProtocol::ClientType clientType) const 
    {
        auto it = m_adapterMap.find(clientType);
        return (it != m_adapterMap.end()) ? it->second : nullptr;
    }
    
    std::vector<UniversalProtocol::ClientType> AdapterManager::getSupportedClientTypes() const 
    {
        std::vector<UniversalProtocol::ClientType> types;
        for (const auto& pair : m_adapterMap) 
        {
            types.push_back(pair.first);
        }
        return types;
    }
    
    void AdapterManager::buildAdapterMap() 
    {
        m_adapterMap.clear();
        for (const auto& adapter : m_adapters) 
        {
            m_adapterMap[adapter->getSupportedClientType()] = adapter.get();
        }
    }
    
    // 全局适配器管理器实例
    AdapterManager& getGlobalAdapterManager() 
    {
        static AdapterManager instance;
        return instance;
    }
    
} // namespace ProtocolAdapters 